package fr.obsmip.sedoo.server.service.dtotool;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.geotoolkit.metadata.iso.extent.DefaultGeographicBoundingBox;
import org.opengis.metadata.extent.GeographicBoundingBox;

import fr.sedoo.commons.client.util.DoubleUtil;
import fr.sedoo.commons.shared.domain.GeographicBoundingBoxDTO;

public class GeographicBoundingBoxDTOTools
{
	public static GeographicBoundingBoxDTO toDTO(GeographicBoundingBox box)
	{
		GeographicBoundingBoxDTO dto = new GeographicBoundingBoxDTO();
		GeographicBoundingBox aux = box;
		if (aux == null)
		{
			aux = new DefaultGeographicBoundingBox();
		}
		dto.setEastBoundLongitude(DoubleUtil.protectNullDouble(aux.getEastBoundLongitude()));
		dto.setWestBoundLongitude(DoubleUtil.protectNullDouble(aux.getWestBoundLongitude()));
		dto.setNorthBoundLatitude(DoubleUtil.protectNullDouble(aux.getNorthBoundLatitude()));
		dto.setSouthBoundLatitude(DoubleUtil.protectNullDouble(aux.getSouthBoundLatitude()));
		return dto;
	}
	
	public static ArrayList<DefaultGeographicBoundingBox> fromDTOList(List<GeographicBoundingBoxDTO> dtoList)
	{
		ArrayList<DefaultGeographicBoundingBox> result = new ArrayList<DefaultGeographicBoundingBox>();
		Iterator<GeographicBoundingBoxDTO> iterator = dtoList.iterator();
		while (iterator.hasNext()) 
		{
			result.add(fromDto(iterator.next()));
		}
		return result;
	}
	
	public static ArrayList<GeographicBoundingBoxDTO> toDTOList(List<GeographicBoundingBox> boxes)
	{
		ArrayList<GeographicBoundingBoxDTO> result = new ArrayList<GeographicBoundingBoxDTO>();
		Iterator<GeographicBoundingBox> iterator = boxes.iterator();
		while (iterator.hasNext()) 
		{
			result.add(toDTO(iterator.next()));
		}
		return result;
	}
	
	

	public static DefaultGeographicBoundingBox fromDto(GeographicBoundingBoxDTO dto)
	{
		if (dto == null)
		{
			return null;
		} else
		{
			DefaultGeographicBoundingBox boundingBox = new DefaultGeographicBoundingBox();

			try
			{
				boundingBox.setEastBoundLongitude(new Double(StringUtils.trimToEmpty(dto.getEastBoundLongitude())));
			} catch (NumberFormatException e)
			{

			}

			try
			{
				boundingBox.setWestBoundLongitude(new Double(StringUtils.trimToEmpty(dto.getWestBoundLongitude())));
			} catch (NumberFormatException e)
			{

			}

			try
			{
				boundingBox.setNorthBoundLatitude(new Double(StringUtils.trimToEmpty(dto.getNorthBoundLatitude())));
			} catch (NumberFormatException e)
			{

			}

			try
			{
				boundingBox.setSouthBoundLatitude(new Double(StringUtils.trimToEmpty(dto.getSouthBoundLatitude())));
			} catch (NumberFormatException e)
			{

			}

			return boundingBox;
		}

	}
}
